package com.example;

import javafx.fxml.FXML;
import javafx.scene.control.Button;
import javafx.scene.control.TextField;
import javafx.stage.Stage;
import javafx.scene.control.Alert;

import java.sql.SQLException;

public class StudentPersonalInformationController implements StudentSubController {

    @FXML
    private TextField usernameField;
    @FXML
    private TextField nameField;
    @FXML
    private TextField typeField;
    @FXML
    private TextField departmentField;
    @FXML
    private TextField statusField;
    @FXML
    private Button saveButton;
    @FXML
    private Button backButton;

    private Stage primaryStage;
    private StudentController studentController;
    private User currentUser;
    private UserDAO userDAO;

    @Override
    public void setPrimaryStage(Stage primaryStage) {
        this.primaryStage = primaryStage;
    }

    @Override
    public void setStudentController(StudentController studentController) {
        this.studentController = studentController;
    }

    public void setCurrentUser(User user) {
        this.currentUser = user;
        populateFields();
    }

    @FXML
    public void initialize() {
        userDAO = new UserDAO();
    }

    private void populateFields() {
        if (currentUser != null) {
            usernameField.setText(currentUser.getUsername());
            nameField.setText(currentUser.getName());
            typeField.setText(currentUser.getType());
            departmentField.setText(currentUser.getDepartment());
            statusField.setText(currentUser.getStatus());
            // 如果添加了联系方式字段，在这里设置
            // contactField.setText(currentUser.getContact());
        }
    }

    @FXML
    private void handleSave() {
        if (currentUser != null) {
            String newName = nameField.getText();
            // 如果添加了联系方式字段，在这里获取
            // String newContact = contactField.getText();

            // 更新User对象
            currentUser.setName(newName);
            // currentUser.setContact(newContact);

            try {
                // 调用DAO更新数据库
                userDAO.updateUser(currentUser); // 需要在UserDAO中实现这个方法
                showAlert(Alert.AlertType.INFORMATION, "成功", "个人信息更新成功！");
            } catch (SQLException e) {
                e.printStackTrace();
                showAlert(Alert.AlertType.ERROR, "错误", "更新个人信息失败：" + e.getMessage());
            }
        } else {
             showAlert(Alert.AlertType.ERROR, "错误", "当前用户信息未加载。");
        }
    }

    @FXML
    private void handleBack() {
        if (studentController != null) {
            studentController.showStudentHomeView();
        } else {
            System.err.println("studentController is null");
        }
    }

    private void showAlert(Alert.AlertType alertType, String title, String message) {
        Alert alert = new Alert(alertType);
        alert.setTitle(title);
        alert.setHeaderText(null);
        alert.setContentText(message);
        alert.showAndWait();
    }
} 